package com.zrb.mobile;

import java.util.List;
import org.apache.http.Header;

 
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.mobile.XList.IXListViewRefreshListener;
import com.zrb.mobile.XList.XListView;
import com.zrb.mobile.adapter.Projectlist_showAdapter;
import com.zrb.mobile.adapter.model.ProjectDtos;
import com.zrb.mobile.adapter.model.ProjectsDto;
import com.zrb.mobile.ui.onLoadMoreListener;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;
 
 

@SuppressLint("ValidFragment")
public  class Project_mainfragment extends BaseImgsFragment implements IXListViewRefreshListener, onLoadMoreListener 
{
 	
	private static final int LOAD_MORE = 0x110;
	private static final int LOAD_REFREASH = 0x111;

	private static final int TIP_ERROR_NO_NETWORK = 0X112;
	private static final int TIP_ERROR_SERVER = 0X113;

	/**
	 * �Ƿ��ǵ�һ�ν���
	 */
	private boolean isFirstIn = true;

	/**
	 * �Ƿ���������
	 */
	private boolean isConnNet = false;

	/**
	 * ��ǰ����Ƿ��Ǵ������л�ȡ��
	 */
	private boolean isLoadingDataFromNetWork;

	/**
	 * Ĭ�ϵ�newType
	 */
	private int newsType =2000;
	/**
	 * ��ǰҳ��
	 */
	private int currentPage = 1;
	/**
	 * �������ŵ�ҵ����
	 */
	//private NewsItemBiz2 mNewsItemBiz;

	/**
	 * ����ݿ⽻��
	 */
	//private NewsItemDao mNewsItemDao;

	/**
	 * ��չ��ListView
	 */
	private XListView mXListView;
	/**
	 * ���������
	 */
	//private NewslistItemAdapter mAdapter;

	/**
	 * ���
	 */
//	private List<NewsItem> mDatas = new ArrayList<NewsItem>();
	TextView mbtnright;
	Projectlist_showAdapter mAdapter2;
	Handler mhandler = new Handler();
 	private String provinceCode="";
	
	/**
	 * ���newType
	 * 
	 * @param newsType
	 */
	public Project_mainfragment()
	{
		//this.newsType = newsType+100;
		//Logger.e(newsType + "newsType");
		//mNewsItemBiz = new NewsItemBiz2();
	}
 	
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
 	    if ((savedInstanceState != null) && savedInstanceState.containsKey("isFirstIn")) {
 	    	isFirstIn = savedInstanceState.getBoolean("isFirstIn");
	    }
		super.onCreate(savedInstanceState);
	}
	
	@Override
	 public  void onSaveInstanceState(Bundle outState) {
        CommonUtil.InfoLog("Project_mainfragment", "start");
        super.onSaveInstanceState(outState);
        outState.putBoolean("isFirstIn", isFirstIn);
    }
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
	 
		if(isVisibleToUser)
		{
			
			Log.e("Project_tabfragment","tab_true" );
		}
		else
		{
			Log.e("Project_tabfragment","tab_false" );
			
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
 		View view = inflater.inflate(R.layout.project_main_fragment, container, false);
		TextView mtitleView=(TextView)view.findViewById(R.id.titleText);
		mtitleView.setText("��Ŀ");
		
	    mbtnright=(TextView)view.findViewById(R.id.moreBtn);
		mbtnright.setVisibility(View.VISIBLE);
		mbtnright.setOnClickListener(new OnClickListener(){
 			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
 				 Intent it = new Intent(Project_mainfragment.this.getActivity(), User_locationActivity.class);
   				 Project_mainfragment.this.startActivityForResult(it, 100);
			}
 		} );
		
		view.findViewById(R.id.searchButton).setVisibility(View.GONE);
      	return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		//mNewsItemDao = new NewsItemDao(getActivity());
	 
		mAdapter2=new Projectlist_showAdapter(getActivity());
		mAdapter2.setImgLoader(imageLoader);
		
		mXListView = (XListView) getView().findViewById(R.id.id_xlistView);
 		if(isFirstIn){
		    LayoutInflater inflater = LayoutInflater.from(this.getActivity());
            View  _bannerView = inflater.inflate(R.layout.ads_banner_fragment, null);
          // mXListView.removeHeaderView(v)
            mXListView.addHeaderView(_bannerView);
		}
  		mXListView.setAdapter(mAdapter2);
		mXListView.setPullRefreshEnable(this);
		mXListView.setOnLoadMoreListener(this);
 
		mXListView.setRefreshTime(CommonUtil.getRefreashTime(getActivity(), newsType));
	 
		// mXListView.NotRefreshAtBegin();

		/*mXListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				 //NewsItem newsItem = mDatas.get(position-1);
				ProjectsDto curDto=mAdapter2.CurrentDatas.get(position-2);
  				Intent intent = new Intent(getActivity(), Project_info_lience.class);
 				intent.putExtra("projectId",(int) curDto.autoId);
 				intent.putExtra("title", curDto.projectName);  
 				startActivity(intent);
			}
 		});*/
 	}

	@Override 
	public void onResume()
	{
		super.onResume();
		if (this.getUserVisibleHint()) firstLoad();
 	}
	
	private void firstLoad()
	{
		if (isFirstIn){
 			isFirstIn = false;
  			mXListView.startRefresh();
		}
		else{
			mXListView.NotRefreshAtBegin();
		}
	}
	
	@Override
	public void onRefresh()
	{
		currentPage=1;
		mhandler.postDelayed(new Runnable(){
	 		   @Override
				public void run() {
	 			   LoadDate("",false,10);
				}
	    }, 10);
	}

	@Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
		currentPage++;
		//LoadDate(mAdapter2.getMinPublishDate(),true,10);
	}
  	
	private void refleshbanner(final List<ProjectsDto> banners){
 
 	    final Ads_banner_fragment fragment2 =(Ads_banner_fragment)this.getFragmentManager().findFragmentById(R.id.ads_banner);
	 	if(fragment2!=null){
 	 		mhandler.postDelayed(new Runnable(){
		 		   @Override
					public void run() {
		 			  fragment2.refleshData(banners);
					}
		    }, 1000);
 	  	}
	}
		 
	private void LoadDate(String time,final boolean isforward,int pagesize)
	{
 		String url=String.format("projectApi/queryProjectApiList?limit=%1$s",10);//&tradeDates=%2$s
 		
 		if(!TextUtils.isEmpty(time)) url+="&pushTime="+time;
   		if(!TextUtils.isEmpty(provinceCode)) url+="&provincePostcode="+provinceCode;
		CommonUtil.InfoLog("url", url);
		
		ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler() {
 			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 				CommonUtil.InfoLog("queryProjectApiList", "onFailure");
  				if(currentPage>1)mXListView.hideloading();
 				else 	mXListView.stopRefresh();
  			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
 				//loadingview.Hide();
 				String results=new String(arg2);
 	 			/*try {
			        Gson gson = new Gson();  
			        ProjectDtos tmpDto=	gson.fromJson(results, ProjectDtos.class);
			        if(tmpDto.res==1){
			        	if(currentPage==1) {
					       mAdapter2.setDatas(tmpDto.data.projectList);
					    }
		 			    else{
		 			        mXListView.hideloading();
		 			        mAdapter2.addAll(tmpDto.data.projectList);
		 			    }
		 	 		    mAdapter2.notifyDataSetChanged();
		 	 		    if(currentPage==1)  refleshbanner(tmpDto.data.bannerList);
 			        }
			        else
			        	CommonUtil.showToast(tmpDto.msg, getActivity());
       			}
				catch(Exception e){
 				   //loadingview.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
					CommonUtil.InfoLog("queryProjectApiList","eeee!!!!"+e.getMessage());
 				}
				CommonUtil.setRefreashTime(getActivity(), newsType);*/
				// ����ˢ��ʱ��
				//mXListView.setRefreshTime(CommonUtil.getRefreashTime(getActivity(), newsType));
				mXListView.stopRefresh();
				 
 			}});
 	 }
 	 
	   @Override
	    public void onActivityResult(int requestCode, int resultCode, Intent data) {
		    if (resultCode == android.app.Activity.RESULT_OK) {
		    	  switch (requestCode) {
		          case 100:
		              String curArea=data.getStringExtra("area");
		              String curCode=data.getStringExtra("code");
		              if(curArea.contains(" ")) 
		            	  showArea(curArea.split(" ")[0],curCode.substring(0, 2)+"0000");
		              else
		            	  showArea(curArea, curCode);
 	                break;
 		         }
		    }
		    super.onActivityResult(requestCode, resultCode, data);
	   }
  	   
	   private void showArea(String areaName,String code){
		   if(areaName.startsWith("����")) 
			   mbtnright.setText("����");
		   else if(areaName.startsWith("���ɹ�"))
			   mbtnright.setText("���ɹ�");
		   else{
 			   mbtnright.setText(CommonUtil.cutString(areaName,2));
		   }
  		   mXListView.update();
 		   currentPage=1;
 		   provinceCode=code;
 		   LoadDate("",false,10);
 	   }

	

}
